package com.eppear.jpfm.framework.websocket.server;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * webSocket 服务器接口类,实现有连接的通讯
 * @author ZJF
 * @date 2017年9月22日 上午11:30:02 
 * 
 */
@ServerEndpoint(value = "/ws/water/{wxid}")
public class WsServer {

	private static final Logger log = LoggerFactory.getLogger(WsServer.class);
	//ConcurrentHashMap 是 Map的线程安全类型
	private static final ConcurrentHashMap<Integer,WsServer> connections =new ConcurrentHashMap<>();
	private Session session;
	private static final AtomicInteger onlineCount = new AtomicInteger(0);
	private AtomicInteger wxId;
	
	WsServer(){
		onlineCount.getAndIncrement();
	}
	@OnOpen
    public void start(Session session,@PathParam("wxid") Integer wxId) {
        //校验连接请求是否合法
		this.wxId =  new AtomicInteger(wxId) ;
		this.session = session;
        connections.put(wxId,this);
        
        log.debug("收到了新的连接请求,wxId={[]},onlineCount={[]}",wxId);
        
    }
	
	@OnClose
	public void end() {
		connections.remove(this.wxId);
		onlineCount.getAndDecrement();
	}
	
	/**
	 *   有新消息时
	 * @author ZJF 
	 * @data   2017-09-23 上午12:07:23
	 * @param message
	 */
	@OnMessage
    public void incoming(String message) {
        // Never trust the client
		
    }
	
	@OnError
    public void onError(Throwable t) throws Throwable {
        log.error("websocket服务器出错: " + t.toString(), t);
    }
	
}
